import { useEffect, useRef, useState } from 'react'
import './style.less'
import { Breadcrumb, Button, Col, Flex, List, Modal, Popover, Rate, Row, Tooltip, notification } from 'antd'
import { HsAdminInput, HsAdminSelect, HsAdminSpin, HsAdminTable, useESPage } from '@hs-admin/base-components'
import {
  Industrcollect,
  Industrdeletecollect,
  IndustryChainList,
  Industryexports,
  Industryexportsall,
  export_daily_counts
} from '@hs-admin/api/sgapi'
import { openCompanyDetail } from 'hs-react-company'
import classNames from 'classnames'
import { EMPTYTEXT, handleButtonShow, message } from '@hs-admin/utils'
import { HonorTreeData, ListingTreeData, ServerEmailModal, companyTypeTreeData, financingTreeData } from '@hs-server/components'
import RangePickerSelect from '@hs-server/components/sgComponents/RangePickerSelect'
import { SearchData } from './SearchData'
import { judgeDataHasMonitors } from '@/api/monitors'
import { MonitorsList } from '@hs-server/components'
import { addmonitorsitems, deletemonitors } from '@/api/home'

const source = 'industryWarning'

interface Props {
  BreadcrumbList: any[]
}
const useRight = (props: Props) => {
  const { BreadcrumbList } = props
  const [data, setData] = useState<any[]>([])
  const [totalNumber, settotalNumber] = useState(0)
  const { ESPage, pagination, resetPage, setPagination } = useESPage({ total: totalNumber, showTotal: false })
  const [searchValue, setsearchValue]: any = useState({
    keywords: null,
    hs_ind_list: {
      column: 'hs_ind_list',
      values: []
    },
    trade_plate: null,
    company_type: null,
    time_scope: {
      start_time: null,
      end_time: null
    },
    qualified: null,
    financing_round: null,
    pca: {
      province_column: 'province_code',
      city_column: 'city_code',
      area_column: 'area_code',
      values: []
    },
    sort: {
      founding_date: null,
      regcapital_amt: null
    }
  })
  const [spreadFlag, setspreadFlag] = useState(false)
  const [counts, setcounts] = useState(0)
  const [selectedRowKeys, setselectedRowKeys]: any = useState([])
  const [api, contextHolder] = notification.useNotification()
  const EmailModalRef = useRef<any>(null)
  const [isModalOpen, setModalOpen] = useState(false)
  const [financing_round, setfinancing_round]: any = useState([]) //融资轮次数据
  const [loading, setloading] = useState(true)
  const [hasInit, sethasInit] = useState(false)
  const conitorsListRef: any = useRef({})
  const monitorItem = useRef<any>({})

  //收藏 取消收藏
  const ChangeRate = (value: any) => {
    let params: any = null

    let iscollect: any = Industrcollect

    let mess: any = null

    if (!value.is_favorite) {
      params = {
        company_ids: [value.id]
      }
      mess = '收藏成功'
    } else {
      params = value.id
      iscollect = Industrdeletecollect

      mess = '取消收藏'
    }

    iscollect(params).then((_res: any) => {
      message.success(mess)
      setPagination({ ...pagination })
    })
  }
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      width: 60,
      render: (_: string, _record: any, index: number) => <>{index + 1 + (pagination.current - 1) * pagination.pageSize}</>
    },
    {
      title: '公司名称',
      dataIndex: 'company_name',
      ellipsis: true,
      width: 240,
      render: (_name: any, row: any) => (
        <Button type="link" onClick={() => openCompanyDetail(row.company_code, source)}>
          {row.company_name}
        </Button>
      )
    },
    {
      title: '全部资质',
      dataIndex: 'qualified_list',
      render: (text: any[]) => <>{text?.length ? text.map((item) => item.name).join(',') : EMPTYTEXT}</>
    },
    {
      title: '所在城市',
      dataIndex: 'province',
      render: (_province: any, row: any) => <>{`${row.province}/${row.city}`}</>
    },
    {
      title: '法人',
      dataIndex: 'legal_rep'
    },
    {
      title: '公司类型',
      dataIndex: 'company_type'
    },
    {
      title: '成立日期',
      dataIndex: 'found_date',
      sorter: true,
      sortDirections: ['descend', 'ascend']
    },
    {
      title: '注册资本（万元）',
      dataIndex: 'regcapital_amt',
      sorter: true,
      sortDirections: ['descend', 'ascend']
    },
    {
      title: '操作',
      dataIndex: 'action',
      render: (_name: any, record: any) => (
        <Flex align="center" gap={'middle'}>
          <Tooltip placement="topLeft" title={record.is_favorite ? '取消收藏' : '收藏'}>
            <Rate count={1} value={record.is_favorite ? 1 : 0} onChange={() => ChangeRate(record)} />
          </Tooltip>
          {!record.ismonitor && (
            <div onClick={() => addmonitorsitem(null, record)}>
              <img src="/static/img/BiomedicalArea/add.png" alt="" className="w-22px cursor-pointer" />
            </div>
          )}
          {record.ismonitor && (
            <div onClick={() => addmonitorsitem(record.company_code, record)}>
              <img src="/static/img/BiomedicalArea/has-add.png" alt="" className="w-22px cursor-pointer" />
            </div>
          )}
        </Flex>
      )
    }
  ]
  const export_counts = () => {
    export_daily_counts().then((res: any) => {
      res.daily_count = res.daily_count > 0 ? 20000 - res.daily_count : 20000
      setcounts(res.daily_count) // 设置导出数量
    })
  }
  const setIsModalOpen = () => {
    if (selectedRowKeys.length > counts) {
      api.warning({
        message: '超过导出限制',
        description: `今日累计导出超过20000条，剩余${counts}条，请重新选择`
      })
      return
    }

    if (selectedRowKeys.length) {
      if (selectedRowKeys.length < 5000) EmailModalRef.current.showModal()
      if (selectedRowKeys.length > 5000 && selectedRowKeys.length < 10000) setModalOpen(true)
      if (selectedRowKeys.length > 10000) {
        api.warning({
          message: '超过导出限制',
          description: `导出超过单次10000数量限制，请重新选择`
        })
      }
      if (selectedRowKeys.length > 500) {
        api.warning({
          message: '超过导出限制',
          description: `导出超过单次数量500，请重新选择`
        })
      }
    } else {
      if (totalNumber > counts && counts !== 20000) {
        api.warning({
          message: '超过导出限制',
          description: `今日累计导出超过20000条，剩余${counts}条，请重新选择`
        })
      } else {
        if (totalNumber < 5000) EmailModalRef.current.showModal()
        if (totalNumber > 5000 && totalNumber < 10000) setModalOpen(true)
        if (totalNumber > 10000) {
          api.warning({
            message: '超过导出限制',
            description: `导出超过单次10000数量限制，请重新选择`
          })
        }
      }
    }
  }
  const handleExport = (obj: any) => {
    let request: any = null
    const params: any = {
      columns: columns.map((item) => ({
        field: item.dataIndex,
        name: item.title
      })),
      filename: obj.filename
    }

    if (selectedRowKeys?.length) {
      params.ids = selectedRowKeys

      request = Industryexports
    } else {
      params.query = searchValue
      request = Industryexportsall
    }
    request(params).then((_res: any) => {
      let messages: any = `提交成功,请在${obj.Email}中查看导出结果`
      export_counts() //更新导出数量值
      if (selectedRowKeys.length) {
        if (selectedRowKeys.length > 5000 && selectedRowKeys.length < 10000) messages = `提交成功，请在个人中心中查看审核结果`
      } else {
        if (totalNumber > 5000 && totalNumber < 10000) messages = `提交成功，请在个人中心中查看审核结果`
      }
      message.success(messages)
      setselectedRowKeys([])
      setModalOpen(false)
    })
  }
  const exportonok = () => {
    setModalOpen(false)
    EmailModalRef.current.showModal()
  }
  function SuccessSearchValue(value: any, type: string) {
    setloading(true)
    //更新搜索数据的方法
    SearchData(setsearchValue, type, value)

    if (type == 'financing_round') {
      setfinancing_round(value)
    }
    resetPage()
  }
  // sorter 列表sort功能 sortOrder代表升序asc还是降序desc field代表当前点击的哪个字段
  const sorter = (sortOrder: any) => {
    let sorttype: any = null

    let field: any = null

    if (sortOrder.field === 'regcapital_amt') {
      field = 'regcapital_amt'
    }

    if (sortOrder.field === 'found_date') {
      field = 'founding_date'
    }
    if (sortOrder.order === 'ascend') {
      sorttype = 'asc'
    } else sorttype = 'desc'

    setsearchValue((prev: any) => {
      prev.sort = {}
      prev.sort[field] = sorttype
      return { ...prev }
    })
    resetPage()
  }
  const addmonitorsitem = (company_code: string | null, record: any) => {
    monitorItem.current = record
    conitorsListRef.current.showModal(company_code)
  }
  const delemonitors = (id: string) => {
    return deletemonitors({ data_id: monitorItem.current.company_code, list_id: id }).then(() => {
      monitorItem.current = {}
      message.success('已取消监测')
      resetPage()
      sethasInit(true)
    })
  }
  const callAddmonitorsitem = (id: any) => {
    if (!monitorItem.current.ismonitor) {
      return addmonitors_items(id)
    } else {
      delemonitors(id)
    }
  }
  const addmonitors_items = (id: any) => {
    return addmonitorsitems({ data_id: monitorItem.current.company_code, list_id: id, data_name: monitorItem.current.company_name }).then(() => {
      monitorItem.current = {}
      message.success('监测成功，在监测模块查看')
      resetPage()
      sethasInit(true)
    })
  }

  useEffect(() => {
    if (hasInit) {
      setloading(true)
      setData([])
      IndustryChainList({
        page: pagination.current,
        page_size: pagination.pageSize,
        ...searchValue
      })
        .then((res) => {
          let { items } = res
          setData(items)
          settotalNumber(res.total)
          const data_ids = items.map((item: { company_code: any }) => item.company_code)
          judgeDataHasMonitors({ data_ids }).then((res2) => {
            items = items.map((item: { company_code: string | number; ismonitor: boolean }) => {
              if (res2[item.company_code]) {
                item.ismonitor = true
              } else {
                item.ismonitor = false
              }
              return item
            })
            setData([...items])
          })
        })
        .finally(() => {
          setloading(false)
        })
    } else {
      setloading(false)
    }
  }, [pagination, hasInit])

  useEffect(() => {
    export_counts()
  }, [])

  return {
    Right: (
      <div className={classNames(['right-box p-4', spreadFlag ? 'right-box-spread' : ''])}>
        {loading && <HsAdminSpin className="right-spin" />}
        <h1 className="module-title">赛道企业</h1>
        <Flex align="center" gap={'middle'} className="my-2">
          <p className="flex-none">当前节点：</p>
          <Breadcrumb separator=">" items={BreadcrumbList} />
        </Flex>
        {!spreadFlag && (
          <HsAdminSelect
            value={searchValue.qualified}
            options={HonorTreeData}
            placeholder="荣誉资质"
            className="w-full"
            mode="multiple"
            onChange={(value: string) => SuccessSearchValue(value, 'qualified')}
          />
        )}
        {spreadFlag && (
          <Flex align="center" gap={'middle'} className="my-2">
            <HsAdminInput
              value={searchValue.keywords}
              Search
              placeholder="请输入公司名称"
              className="w-240px"
              onChange={(e: { target: { value: any } }) => {
                setsearchValue((prev: { keywords: any }) => {
                  prev.keywords = e.target.value
                  return { ...prev }
                })
              }}
              onSearch={(value: string) => {
                setsearchValue((prev: { keywords: string | null }) => {
                  prev.keywords = value || null
                  return { ...prev }
                })
                resetPage()
              }}
              onPressEnter={(e: { target: { value: string } }) => {
                setsearchValue((prev: { keywords: string | null }) => {
                  prev.keywords = e.target?.value || null
                  return { ...prev }
                })
                resetPage()
              }}
            />
            <Button
              type="link"
              onClick={() => {
                setsearchValue(
                  (prev: {
                    keywords: null
                    hs_ind_list: { column: string; values: never[] }
                    trade_plate: null
                    company_type: null
                    time_scope: { start_time: null; end_time: null }
                    qualified: null
                    financing_round: null
                    pca: { province_column: string; city_column: string; area_column: string; values: never[] }
                    sort: { founding_date: null; regcapital_amt: null }
                  }) => {
                    prev = {
                      keywords: null,
                      hs_ind_list: {
                        column: 'hs_ind_list',
                        values: []
                      },
                      trade_plate: null,
                      company_type: null,
                      time_scope: {
                        start_time: null,
                        end_time: null
                      },
                      qualified: null,
                      financing_round: null,
                      pca: {
                        province_column: 'province_code',
                        city_column: 'city_code',
                        area_column: 'area_code',
                        values: []
                      },
                      sort: {
                        founding_date: null,
                        regcapital_amt: null
                      }
                    }
                    return { ...prev }
                  }
                )
                setfinancing_round([])
                resetPage()
              }}>
              重置搜索
            </Button>
          </Flex>
        )}
        {spreadFlag && (
          <Row className="my-2" gutter={16}>
            <Col span="4">
              <HsAdminSelect
                value={searchValue.qualified}
                options={HonorTreeData}
                placeholder="荣誉资质"
                className="w-full"
                mode="multiple"
                onChange={(value: string) => SuccessSearchValue(value, 'qualified')}
              />
            </Col>
            <Col span="4">
              <HsAdminSelect
                value={searchValue.trade_plate}
                options={ListingTreeData}
                placeholder="上市情况"
                className="w-full"
                mode="multiple"
                onChange={(value: string) => SuccessSearchValue(value, 'trade_plate')}
              />
            </Col>
            <Col span="4">
              <HsAdminSelect
                value={financing_round}
                options={financingTreeData}
                placeholder="融资情况"
                className="w-full"
                mode="multiple"
                onChange={(value: string) => SuccessSearchValue(value, 'financing_round')}
              />
            </Col>
            <Col span="4">
              <HsAdminSelect
                value={searchValue.company_type}
                options={companyTypeTreeData}
                placeholder="公司类型"
                className="w-full"
                mode="multiple"
                onChange={(value: string) => SuccessSearchValue(value, 'company_type')}
              />
            </Col>
            <Col span="8">
              <Flex align="center" gap={'small'}>
                <span>成立日期：</span>
                <RangePickerSelect
                  modelValue={searchValue.time_scope}
                  success={(values: any) => SuccessSearchValue(values ? values : null, 'time_scope')}
                />
              </Flex>
            </Col>
          </Row>
        )}
        <Flex align="center" gap={'middle'} className="my-2" justify="space-between">
          <div className="my-3">共 {totalNumber} 家</div>
          {handleButtonShow('sg.export.limit.20000') && (
            <Popover
              arrow={false}
              content={
                <div>
                  {contextHolder}
                  今日还能导出 <span className="text-orange-500"> {counts}</span>条
                </div>
              }>
              <Button type="link" shape="round" onClick={setIsModalOpen}>
                <img src="/static/img/BiomedicalArea/download.png" alt="" className="w-16px mr-2" />
                {selectedRowKeys.length ? `导出(${selectedRowKeys.length})` : '导出excel'}
              </Button>
            </Popover>
          )}
        </Flex>
        <div className={classNames(['max-h-136 overflow-y-auto', spreadFlag ? 'max-h-100' : ''])}>
          {!spreadFlag && (
            <List
              size="small"
              bordered
              dataSource={data}
              renderItem={(item) => (
                <List.Item>
                  <Button type="link" onClick={() => openCompanyDetail(item.company_code, source)}>
                    {item.company_name}
                  </Button>
                </List.Item>
              )}
            />
          )}
          {spreadFlag && (
            <HsAdminTable
              columns={columns}
              dataSource={data}
              rowKey="id"
              pagination={false}
              scroll={{ x: 1500 }}
              size="small"
              onChange={(_a: any, _b: any, sortOrder: any) => sorter(sortOrder)}
            />
          )}
        </div>
        <Flex justify="flex-end">{ESPage}</Flex>
        <div
          className="spread-btn"
          onClick={() => {
            setspreadFlag(!spreadFlag)
          }}>
          <p></p>
        </div>
        <ServerEmailModal ref={EmailModalRef} success={handleExport} title={'导出数据'}></ServerEmailModal>
        <Modal
          title={'单次导出超出5000条，需要通过审批才能导出，是否继续？'}
          open={isModalOpen}
          onCancel={() => setModalOpen(false)}
          onOk={exportonok}></Modal>
        <MonitorsList ref={conitorsListRef} addmonitorsitem={callAddmonitorsitem} />
      </div>
    ),
    updateAreaSearch: (arr: () => IterableIterator<any>) => {
      setsearchValue((prev: { pca: any[] }) => {
        prev.pca.values = arr
        return { ...prev }
      })
      resetPage()
    },
    updateHsIndSearch: (values: any) => {
      setsearchValue((prev: { hs_ind_list: any }) => {
        prev.hs_ind_list = {
          column: 'hs_ind_list',
          values
        }
        return { ...prev }
      })
      resetPage()
      sethasInit(true)
    }
  }
}

export default useRight
